#pragma once

#include <fstream>
#include <iomanip>  // 用于 std::hex, std::setw
#include <iostream> // 用于 std::cout
#include <stdexcept>
#include <vector>

// 整个类加载二进制文件(比如mysql、postgresql的抓包数据)进入一个缓存
class BinaryFileReader {
  public:
    // 加载二进制文件
    static std::vector<uint8_t> loadBinaryFile(const std::string &filename) {
        std::ifstream file(filename, std::ios::binary | std::ios::ate);
        if (!file) {
            throw std::runtime_error("Failed to open file: " + filename);
        }

        std::streamsize size = file.tellg();
        file.seekg(0, std::ios::beg);

        std::vector<uint8_t> buffer(size);
        if (!file.read(reinterpret_cast<char *>(buffer.data()), size)) {
            throw std::runtime_error("Failed to read file: " + filename);
        }

        return buffer;
    }

    // 以十六进制格式打印二进制数据
    static void printHex(const std::vector<uint8_t> &data, int bytesPerLine = 8) {
        std::cout << "Binary file content (hex):" << std::endl;
        for (size_t i = 0; i < data.size(); ++i) {
            // 每个字节以 2 位十六进制显示，不足补 0
            std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(data[i]) << " ";

            // 每行显示 bytesPerLine 个字节
            if ((i + 1) % bytesPerLine == 0 || i == data.size() - 1) {
                std::cout << std::endl;
            }
        }
        std::cout << std::dec; // 恢复十进制输出
    }
};